package com.hkemmm.shop.utlis;

import com.hkemmm.shop.entity.Email_Authenticator;

import javax.mail.*;
import javax.mail.internet.*;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;

/**
 * 封装邮件发送工具类
 */
public class SendEmail {
    /*public static void main(String[] args) {
        try {
            send_email(new String[]{"H_fanwb@163.com","2390382153@qq.com"},"测试","你好！");
        } catch (AddressException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }*/

    public static void send_email(String toEmail, String subjects, String contents) throws IOException, AddressException, MessagingException {

        String recevie = toEmail;
        String subject = subjects;
        String content = contents;
        // 跟smtp服务器建立一个连接
        Properties properties = new Properties();
        //设置邮件服务器主机名
        properties.put("mail.smtp.host", "smtp.qq.com");
        properties.put("mail.smtp.port", "25");
        // 发送服务器需要身份验证,要采用指定用户名密码的方式去认证
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.transport.protocol", "smtp");

        Authenticator authenticator = new Email_Authenticator("1767231087@qq.com", "rdgpkskrpkhbbfec");
        javax.mail.Session sendMailSession = javax.mail.Session.getDefaultInstance(properties, authenticator);
        MimeMessage mailMessage = new MimeMessage(sendMailSession);
        mailMessage.setFrom(new InternetAddress("1767231087@qq.com"));

        // Message.RecipientType.TO属性表示接收者的类型为TO
        //多个收件人把String数组转换InternetAddress数组
//        InternetAddress[] internetAddresses = new InternetAddress[to.length];
//        for (int i = 0; i < internetAddresses.length; i++){
//            internetAddresses[i] = new InternetAddress(to[i]);
//        }

        //InternetAddress internetAddress = new InternetAddress(recevie);

        //mailMessage.setRecipients(Message.RecipientType.TO, internetAddresses);
        mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(recevie));
        //邮件主题
        mailMessage.setSubject(subject, "UTF-8");
        mailMessage.setSentDate(new Date());

        // MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象
        Multipart mainPart = new MimeMultipart();

        // 创建一个包含HTML内容的MimeBodyPart
        BodyPart html = new MimeBodyPart();
        //邮件内容,转换为html形式
        html.setContent(content.trim(), "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        mailMessage.setContent(mainPart);


        Transport.send(mailMessage);
        System.out.println("发送成功！");
    }
}

